package com.vip.flushdemo;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.vip.entities.TaskOfZB;
import com.vip.utilities.JsonHelper;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by francis on 2016/9/20.
 */
public class MainActiivity1 extends ListActivity implements PullToRefreshBase.OnRefreshListener2<ListView> {
    private PullToRefreshListView listView1;
    private List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
    private SimpleAdapter adapter;// 数据Adapter
    private String apiUrl = "http://103.204.179.62:8888/tpa/getbypagenumber?pn=";
    private int currentPageNumber = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView1 = (PullToRefreshListView) findViewById(R.id.myPull_refresh_list);

        adapter = new SimpleAdapter(
                this,
                getDataItems(),
                R.layout.activity_list_item,
                new String[]{"title", "info", "img", "des"},
                new int[]{R.id.title, R.id.info, R.id.img, R.id.des});

        listView1.setAdapter(adapter);

        listView1.setOnRefreshListener(this);// 记得绑定一下 监听类
    }

    private static String doGet(String url) throws Exception {
        URL localURL = new URL(url);
        URLConnection connection = localURL.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }

        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);

            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }

        } finally {

            if (reader != null) {
                reader.close();
            }

            if (inputStreamReader != null) {
                inputStreamReader.close();
            }

            if (inputStream != null) {
                inputStream.close();
            }

        }

        return resultBuffer.toString();
    }


    private List<Map<String, Object>> getDataItems() {
        String strJsonString = "";
        try {
            strJsonString = doGet(apiUrl + currentPageNumber);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (strJsonString == "") {
            return lists;
        }

        List<TaskOfZB> tmpData = JsonHelper.fromJson(strJsonString, new TypeToken<ArrayList<TaskOfZB>>() {
        }.getType());
        getListItems(tmpData);

        return lists;
    }

    private void getListItems(List<TaskOfZB> data) {
        if (data == null || data.size() <= 0) {
            return;
        }
        for (TaskOfZB task : data) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("title", task.getTitle());
            map.put("info", task.getPriceDescirtion());
            map.put("img", R.drawable.ic_launcher);
            map.put("des", task.getDescription());
           // map.put("id_id", UUID.randomUUID().toString());
            lists.add(map);
        }
    }

    // 异步方式模拟请求数据
    private class GetDataTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            adapter.notifyDataSetChanged();// 刷新Adapter
            listView1.onRefreshComplete();// 告诉它 我们已经在后台数据请求完毕
            Toast.makeText(MainActiivity1.this, "加载完成", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected Integer doInBackground(Integer... params) {
            try {
                getDataItems();// 继续刷数据
            } catch (Exception e) {
                e.printStackTrace();
            }
            publishProgress(0);//通知前台线程
            return 0;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        // Toast.makeText(this, "下拉", Toast.LENGTH_SHORT).show();
        currentPageNumber = 1;// 刷新数据
        lists.clear();
        new GetDataTask().execute();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        //Toast.makeText(this, "上拉", Toast.LENGTH_SHORT).show();
        currentPageNumber++;
        new GetDataTask().execute();
    }
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        //super.onListItemClick(l, v, position, id);

    }
}
